<?php
/**
 * @author      Alex Bilbie <hello@alexbilbie.com>
 * @copyright   Copyright (c) Alex Bilbie
 * @license     http://mit-license.org/
 *
 * @link        https://github.com/thephpleague/oauth2-server
 */

namespace app\components\oauth2\repositories;

use app\helpers\Redis;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
use app\components\oauth2\entities\AuthCodeEntity;

class AuthCodeRepository implements AuthCodeRepositoryInterface
{
    const PREFIX = 'auth_code:';
    /**
     * {@inheritdoc}
     */
    public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity)
    {
        $redis = Redis::getRedis();
        $codeId = $authCodeEntity->getIdentifier();
        $expiryDateTime = $authCodeEntity->getExpiryDateTime()->getTimestamp();
        $seconds = $expiryDateTime - \time();
        $redis->set(self::PREFIX.$codeId,$authCodeEntity->getClient()->getIdentifier(),['EX'=>$seconds]);
    }

    /**
     * {@inheritdoc}
     */
    public function revokeAuthCode($codeId)
    {
        $redis = Redis::getRedis();
        $redis->del(self::PREFIX.$codeId);
    }

    /**
     * {@inheritdoc}
     */
    public function isAuthCodeRevoked($codeId)
    {
        $redis = Redis::getRedis();
        return !$redis->exists(self::PREFIX.$codeId);
    }

    /**
     * {@inheritdoc}
     */
    public function getNewAuthCode()
    {
        return new AuthCodeEntity();
    }
}